import { getData, deleteData } from "@/api/common";
import { formatTime } from "@/utils";
import { ref, computed, onMounted, reactive } from "vue";
import { download } from "@/utils/csv.js";
export default function useQueryTable(url, form, opt = {}, tableColumn) {
  //基础配置参数
  let list = ref([]);
  let loading = ref(false);
  let downloading = ref(false);
  let total = ref(0);
  let page = reactive({
    pageSize: 10,
    pageIndex: 1,
  });

  const params = computed(() => {
    let time = {};
    if (opt.time) {
      time = {
        startTime: opt.format
          ? formatTime(form.time[(0, opt.format)])
          : form.time[0],
        endTime: opt.format
          ? formatTime(form.time[1], opt.format)
          : form.time[1],
      };
    }
    return {
      ...time,
      ...form,
      ...page,
    };
  });
  const options = computed(() => {
    return {
      loading: loading.value,
      showPagination: opt?.showPagination ?? true,
      rowKey: "id",
      defaultExpandAll: false,
      border: true,
      paginationConfig: {
        total: total.value,
        currentPage: page.pageIndex,
        pageSize: page.pageSize,
      },
    };
  });

  //  编辑相关
  let editOption = reactive({
    show: false,
    type: "add",
    data: {},
  });
  function handlerEdit(row) {
    editOption.show = true;
    editOption.type = "edit";
    editOption.data = row;
  }
  function closeDialog(val) {
    editOption.show = false;
    val && query();
  }

  function addForm() {
    editOption.show = true;
    editOption.type = "add";
    editOption.data = [];
  }

  //查询相关
  onMounted(() => {
    query();
  });

  function query() {
    page.pageIndex = 1;
    getTable();
  }

  async function output(name, transform = {}) {
    try {
      downloading.value = true;
      let header = {};
      tableColumn.forEach((item) => {
        if (item.prop) {
          header[item.prop] = item.label;
        }
      });
      let dataSource = [];
      let param = JSON.parse(JSON.stringify(params.value));
      delete param.pageIndex;
      delete param.pageSize;
      let res = await getData(url.get, param);
      dataSource = res?.items ?? [];

      await download(
        name,
        dataSource,
        {
          header: true,
          transform: transform,
        },
        header
      );
      downloading.value = false;
    } catch (e) {
      downloading.value = false;
    }
  }

  async function getTable() {
    try {
      loading.value = true;
      list.value = [];
      let res = await getData(url.get, params.value);
      list.value = res.items || [];
      total.value = res.totalCount || 0;
      loading.value = false;
    } catch (e) {
      loading.value = false;
      console.error(e);
    }
  }

  function handlerDel(id) {
    ElMessageBox.confirm(`是否确认删除该物料?`, "提示", {
      confirmButtonText: "确 定",
      cancelButtonText: "取 消",
      type: "warning",
    })
      .then(async () => {
        let res = await deleteData(url.del, [id]);
        if (res) {
          ElMessage.success("删除成功");
          getTable();
        }
      })
      .catch(() => {
        return false;
      });
  }
  const handleAction = (command, row) => {
    switch (command) {
      case "edit":
        handlerEdit(row);
        break;
      case "delete":
        handlerDel(row.id);
        break;
      default:
        break;
    }
  };

  // 表请求条数改变
  const handlerPageSize = (pageSize) => {
    page.pageSize = pageSize;
    page.pageIndex = 1;
    getTable();
  };
  // 表格页数改变
  const handlerPageIndex = (pageIndex) => {
    page.pageIndex = pageIndex;
    getTable();
  };

  return {
    list,
    total,
    query,
    output,
    options,
    addForm,
    loading,
    editOption,
    downloading,
    handlerDel,
    handlerEdit,
    closeDialog,
    handleAction,
    handlerPageSize,
    handlerPageIndex,
  };
}
